using System;
using Microsoft.SPOT;
using System.Net.Sockets;
using Microsoft.SPOT.Hardware;
using System.Net;
using SecretLabs.NETMF.Hardware.NetduinoPlus;
using System.Text;
using System.Threading;
using DaaseVarmer.helperClasses;
using DaaseVarmer.domain;
using System.IO;
using DaaseVarmer.webserver.framework;


namespace DaaseVarmer.webserver.impl
{
    public class WebServer
    {
        private OutputPort _led = new OutputPort(Pins.ONBOARD_LED, false);
        private HttpListener _listener;
        private IRequestHandler _reqHandler;
        private LogManager _logmanager = LogManager.Instance;

        public WebServer(int port)
        {
            _listener = new HttpListener("http", port);
            _reqHandler = new RequestHandler();
        }


        public void listenForRequest()
        {
            _listener.Start();
            Debug.Print(GetIp());

            while (true)
            {
                try
                {
                    FlashLED(_led);
                    HttpListenerContext c = _listener.GetContext();
                    byte[] buffer = _reqHandler.GetResponse(c.Request);
                    c.Response.ContentLength64 = buffer.Length;
                    c.Response.OutputStream.Write(buffer, 0, buffer.Length);
                    c.Response.OutputStream.Close();
                }
                catch (Exception)
                {
                    _logmanager.Error("Exception in WebServer:listenForRequest()");
                }
            }
        }

        private void FlashLED(OutputPort led)
        {
            led.Write(true);
            Thread.Sleep(150);
            led.Write(false);
        }

        private String GetIp()
        {
            return Microsoft.SPOT.Net.NetworkInformation.NetworkInterface.GetAllNetworkInterfaces()[0].IPAddress;
        }

    }        
}